package com.ruoyi.web.controller.portal;

import com.aliyun.oss.model.OSSObjectSummary;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.portal.service.FileUploadService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author: cjie
 * @description:
 * @date: 2021/5/9
 */
@RestController
@RequestMapping("/portal/file")
public class FileUploadController {
    @Resource
    private FileUploadService fileUploadService;

    /**
     * 文件上传
     * @param uploadFile
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile uploadFile)
            throws Exception {
        return this.fileUploadService.upload(uploadFile);
    }

    /**
     * 文件删除
     * @param objectName  指包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
     * @return
     * @throws Exception
     */
    @RequestMapping("/delete")
    public AjaxResult delete(@RequestParam("fileName") String objectName)
            throws Exception {
        return this.fileUploadService.delete(objectName);
    }

    /**
     * 查询oss上的所有文件
     * @return
     * @throws Exception
     */
    @GetMapping("/list")
    public List<OSSObjectSummary> list()
            throws Exception {
        return this.fileUploadService.list();
    }

    /**
     * 根据文件名下载oss上的文件
     * @return
     * @Param objectName 指包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
     */
    @RequestMapping("/download")
    public void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {
        //通知浏览器以附件形式下载
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(objectName.getBytes(), "ISO-8859-1"));
        this.fileUploadService.exportOssFile(response.getOutputStream(),objectName);
    }
}
